package com.example.jetpackcomposelearning.compose

import android.content.Intent
import android.net.Uri
import android.view.View
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.example.jetpackcomposelearning.R
import com.example.jetpackcomposelearning.VideoPlayerActivity
import com.example.jetpackcomposelearning.util.MediaService
import com.example.jetpackcomposelearning.util.Uri2PathUtil
import com.example.jetpackcomposelearning.viewModel.ImagePickerViewModel
import java.io.File
import java.util.concurrent.Executors

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ImagePickerScreen(onPickImagesClick: () -> Unit) {
    val viewModel: ImagePickerViewModel = hiltViewModel()
    val images = viewModel.imageList.collectAsState(initial = emptyList())
    val selectedImagePath = viewModel.selectedImagePath.collectAsState(initial = null)
    val isComposeDialogVisible by viewModel.isComposeDialogVisible.collectAsState()
    val fileTitle by viewModel.fileTitle.collectAsState()
    val context = LocalContext.current

    var dialogTextFieldValue by remember { mutableStateOf(TextFieldValue(fileTitle)) }

    Scaffold(
        topBar = {
            TopAppBar(title = { Text("情景创作") })
        },
        floatingActionButton = {
            FloatingActionButton(onClick = onPickImagesClick) {
                Icon(Icons.Default.Add, contentDescription = "Add Images")
            }
        },
        content = { padding ->
            Column(modifier = Modifier.fillMaxSize().padding(padding)) {
                // 合成按钮行
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 10.dp, vertical = 8.dp),
                    horizontalArrangement = Arrangement.End
                ) {
                    Button(onClick = {
                        viewModel.showComposeDialog()
                    }) {
                        Text("合成")
                    }
                }

                if (images.value.isEmpty()) {
                    Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                        CircularProgressIndicator()
                    }
                } else {
                    Row(modifier = Modifier.fillMaxSize()) {
                        if (selectedImagePath.value != null) {
                            // 显示大图
                            Box(
                                modifier = Modifier
                                    .weight(1f)
                                    .fillMaxHeight()
                                    .padding(horizontal = 10.dp)
                                    .clickable { viewModel.clearSelection() }
                            ) {
                                AsyncImage(
                                    model = ImageRequest.Builder(LocalContext.current)
                                        .data(selectedImagePath.value)
                                        .crossfade(true)
                                        .build(),
                                    placeholder = painterResource(R.drawable.ic_placeholder),
                                    error = painterResource(R.drawable.ic_error),
                                    contentDescription = null,
                                    contentScale = ContentScale.Fit,
                                    modifier = Modifier
                                        .fillMaxSize()
                                        .clip(MaterialTheme.shapes.large)
                                )
                            }
                        } else {
                            Spacer(modifier = Modifier.weight(1f))
                        }

                        // 显示图片列表
                        Box(
                            modifier = Modifier
                                .weight(1f)
                                .padding(horizontal = 10.dp)
                        ) {
                            LazyVerticalGrid(
                                columns = GridCells.Fixed(3),
                                modifier = Modifier.fillMaxSize()
                            ) {
                                items(images.value.size) { index ->
                                    val imagePath = images.value[index]
                                    Column(
                                        horizontalAlignment = Alignment.CenterHorizontally,
                                        verticalArrangement = Arrangement.Center,
                                        modifier = Modifier.padding(4.dp)
                                    ) {
                                        AsyncImage(
                                            model = ImageRequest.Builder(LocalContext.current)
                                                .data(imagePath)
                                                .crossfade(true)
                                                .build(),
                                            placeholder = painterResource(R.drawable.ic_placeholder),
                                            error = painterResource(R.drawable.ic_error),
                                            contentDescription = null,
                                            contentScale = ContentScale.Crop,
                                            modifier = Modifier
                                                .size(100.dp)
                                                .clip(MaterialTheme.shapes.medium)
                                                .clickable { viewModel.selectImage(imagePath) }
                                        )
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // 弹出输入文件标题的对话框
            if (isComposeDialogVisible) {
                AlertDialog(
                    onDismissRequest = { viewModel.hideComposeDialog() },
                    title = { Text("输入合成视频标题") },
                    text = {
                        TextField(
                            value = dialogTextFieldValue,
                            onValueChange = { newValue ->
                                dialogTextFieldValue = newValue
                                viewModel.setFileTitle(newValue.text)
                            },
                            label = { Text("视频标题") },
                            placeholder = { Text("请输入合成视频标题") }
                        )
                    },
                    confirmButton = {
                        TextButton(onClick = {
                            val title = viewModel.getCombineVideoTitle()
                            val selectedImages = viewModel.getCombineImageList()
                            val selectedImagePaths = mutableListOf<Uri>()
                            selectedImages.forEach { imageUri ->
                                selectedImagePaths.add(Uri.fromFile(File(Uri2PathUtil.getRealPathFromUri(context, Uri.parse(imageUri)))))
                            }
                            if (title.isNotEmpty()) {
                                val combinedVideo = "/data/data/com.example.jetpackcomposelearning/files/combinedVideo_${title}.mp4"
                                val executorService = Executors.newFixedThreadPool(1)
                                executorService.execute(kotlinx.coroutines.Runnable {
                                    val combineVideoOperationResult = MediaService.combineFromMaterials(selectedImagePaths, "", "", Uri.fromFile(
                                        File(combinedVideo)
                                    ))
                                    (context as? ComponentActivity)?.runOnUiThread {
                                        if(combineVideoOperationResult && File(combinedVideo).exists()){
                                            val intent = Intent(context, VideoPlayerActivity::class.java)
                                            intent.putExtra("video_path", combinedVideo)
                                            context.startActivity(intent)
                                            context.finish()
                                        }else{
                                            val toast = Toast(context)
                                            toast.setText("合成失败")
                                            toast.duration = Toast.LENGTH_SHORT
                                            toast.show()
                                        }

                                    }
                                })


                            }
                        }) {
                            Text("确定")
                        }
                    },
                    dismissButton = {
                        TextButton(onClick = { viewModel.hideComposeDialog() }) {
                            Text("取消")
                        }
                    }
                )
            }
        }
    )
}